package com.ruoyi.yipaiju.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.yipaiju.domain.DifyFlow;
import com.ruoyi.yipaiju.domain.ForeclosedHouse;
import com.ruoyi.yipaiju.service.IForeclosedHouseService;
import com.ruoyi.yipaiju.service.IXcxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 尽调报告订单Controller
 * 
 * @author liuwp
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/yipaiju/dify_flow")
public class DifyFlowController extends BaseController
{


    @Autowired
    private IXcxUserService xcxUserService;
    @Autowired
    private IForeclosedHouseService foreclosedHouseService;

    /**
     * 查询尽调报告订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DifyFlow difyFlow)
    {

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        HttpRequest request = new HttpRequest();
        request.addHeader("Content-Type", "application/json;charset=utf-8");

        String data = "{\n" +
                "  \"dialog_carrier\": \"dify_ypj\",\n" +
                "  \"page\": \""+pageNum+"\",\n" +
                "  \"pagesize\": \""+pageSize+"\"\n" +
                "}";
        HttpRespons response = request.sendPost(RuoYiConfig.getDifyApi() + "/erp/user_house_combinations", data);

        if (response != null && response.getCode() == 200) {
            JSONObject jsonObject = JSONObject.parseObject(response.getContent());
            JSONObject dataObject = jsonObject.getJSONObject("data");
            int total = dataObject.getInteger("total");
            JSONArray dataList = dataObject.getJSONArray("data");

            // 获取所有用户
            List<XcxUser> userList = xcxUserService.selectXcxUserList(new XcxUser());
            Map<Long, XcxUser> userMap = userList.stream().collect(Collectors.toMap(XcxUser::getId, a -> a));

            List<DifyFlow> list = new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject item = (JSONObject) dataList.get(i);
                DifyFlow df = new DifyFlow();
                df.setId(String.valueOf(i));
                df.setXcxUserId(item.getLong("user"));
                df.setXcxUserName(df.getXcxUserId().toString());
                df.setHouseId(item.getLong("houses_id"));
                df.setHouseTitle(df.getHouseId().toString());
                XcxUser xcxUser = userMap.get(df.getXcxUserId());
                if (xcxUser != null) {
                    df.setXcxUserName(xcxUser.getNickname());
                    df.setXcxUserAvatar(xcxUser.getAvatarUrl());
                }
                // TODO 暂时先这样
                ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(df.getHouseId());
                if (foreclosedHouse != null) {
                    df.setHouseTitle(foreclosedHouse.getTitle());
                    df.setHouseHref(foreclosedHouse.getAuctionUrl());
                }

                df.setCreateTime(item.getDate("latest_time"));
                df.setUserQuestion(item.getString("latest_question"));
                df.setAiOutput(item.getString("latest_response"));
                list.add(df);
            }

            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);
            return rspData;
        }else {
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 获取尽调报告订单详细信息
     */
    @GetMapping(value = "/getInfo")
    public TableDataInfo getInfo(DifyFlow difyFlow)
    {
        HttpRequest request = new HttpRequest();
        request.addHeader("Content-Type", "application/json;charset=utf-8");

        String data = "{\n" +
                "  \"dialog_carrier\": \"dify_ypj\",\n" +
                "  \"user_id\": \""+difyFlow.getXcxUserId()+"\",\n" +
                "  \"house_id\": \""+difyFlow.getHouseId()+"\",\n" +
                "  \"page\": \"1\",\n" +
                "  \"pagesize\": \"1000\"\n" +
                "}";
        HttpRespons response = request.sendPost(RuoYiConfig.getDifyApi() + "/erp/select_order_history_with_pagination", data);

        if (response != null && response.getCode() == 200) {
            JSONObject jsonObject = JSONObject.parseObject(response.getContent());
            JSONObject dataObject = jsonObject.getJSONObject("data");
            JSONArray dataList = dataObject.getJSONArray("data");
            int total = dataObject.getInteger("total");

            // 获取所有用户
            List<XcxUser> userList = xcxUserService.selectXcxUserList(new XcxUser());
            Map<Long, XcxUser> userMap = userList.stream().collect(Collectors.toMap(XcxUser::getId, a -> a));

            List<DifyFlow> list = new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject item = (JSONObject) dataList.get(i);
                DifyFlow df = new DifyFlow();
                df.setId(String.valueOf(i));
                df.setXcxUserId(difyFlow.getXcxUserId());
                df.setXcxUserName(df.getXcxUserId().toString());
                df.setHouseId(df.getXcxUserId());
                df.setHouseTitle(df.getHouseId().toString());
                XcxUser xcxUser = userMap.get(df.getXcxUserId());
                if (xcxUser != null) {
                    df.setXcxUserName(xcxUser.getNickname());
                    df.setXcxUserAvatar(xcxUser.getAvatarUrl());
                }
                ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(df.getHouseId());
                if (foreclosedHouse != null) {
                    df.setHouseTitle(foreclosedHouse.getTitle());
                    df.setHouseHref(foreclosedHouse.getAuctionUrl());
                }

                df.setCreateTime(item.getDate("create_time"));
                df.setUserQuestion(item.getString("user_question"));
                df.setAiOutput(item.getString("api_output"));
                list.add(df);
            }
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);
            return rspData;
        }
        return getDataTable(new ArrayList<>());
    }

}
